import React, {useContext, useEffect, useState} from 'react';
import {StatusBar, ImageBackground, View, TextInput, Dimensions} from 'react-native';
import { Button, Image, Text } from 'react-native-elements';

import LocaleContext from '../libs/locale';
import AsyncStorage from "@react-native-async-storage/async-storage";
import WalletContext from "../libs/wallet";
import {TouchableHighlight} from "react-native-gesture-handler";
import Toast from "react-native-simple-toast";
import {constansts} from "../libs/constansts";
import {bytes2Hex, keyPairFromSeed, randomSeed, toAddress} from "../libs/keyPair";
import {convertKeyPair} from "../libs/ed2curve";
import {enAES, joinGroup} from "../libs/chatGroup";

const {width,height,scale} = Dimensions.get("window");

const ChatGroupCreate = ({ navigation,route }: any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);

    const[ChatGroupName,setChatGroupName] = useState("")

    const createWalletKeyPair = () => {
        const seed = randomSeed();
        const keyPair: any = keyPairFromSeed(seed);
        const address = toAddress(keyPair.publicKey);
        return keyPair;
    }

    const createChatGroup = async () => {
        let nacl = require("tweetnacl");
        let wallet1_KeyPair = createWalletKeyPair();
        let wallet2_KeyPair = createWalletKeyPair();
        let wallet1_Priv = bytes2Hex(wallet1_KeyPair.secretKey);
        let wallet2_Priv = bytes2Hex(wallet2_KeyPair.secretKey);
        console.log(`wallet1Priv:${wallet1_Priv}`)
        console.log(`wallet2Priv:${wallet2_Priv}`)

        let DHKey1: any = convertKeyPair(wallet1_KeyPair);
        let DHKey2: any = convertKeyPair(wallet2_KeyPair);
        var s1 = nacl.box.before(DHKey1.publicKey, DHKey2.secretKey);
        var s2 = nacl.box.before(DHKey2.publicKey, DHKey1.secretKey);
        let s1_key = bytes2Hex(s1)
        let s2_key = bytes2Hex(s2)
        console.log(`s1Key:${s1}`)
        console.log(`s2Key:${s2}`)

        let Q_Address = toAddress(wallet1_KeyPair.publicKey);
        console.log("Q_Address:"+Q_Address)

        let myChatGroupList = [];
        let myChatGroupListStr = await AsyncStorage.getItem("myChatGroupList");
        if (myChatGroupListStr) {
            myChatGroupList = JSON.parse(myChatGroupListStr);
        }
        console.log(JSON.stringify({addressOut:Q_Address,Creator:wallet.address,Key:s1_key,desc:ChatGroupName,Voucher:wallet1_Priv+wallet2_Priv,type:"Gchat"}))
        myChatGroupList.push({addressOut:Q_Address,Creator:wallet.address,Key:s1_key,desc:ChatGroupName,Voucher:wallet1_Priv+wallet2_Priv,type:"Gchat"})
        await joinGroup(wallet.address,wallet.address,ChatGroupName,enAES(wallet.seed,s1_key),Q_Address,enAES(wallet.seed,wallet1_Priv+wallet2_Priv))
        console.log(JSON.stringify(myChatGroupList))
        await AsyncStorage.setItem("myChatGroupList",JSON.stringify(myChatGroupList));
        navigation.navigate("ChatGroupView",{Q_Address:Q_Address,Q_Key:s1_key,QP_Priv:wallet1_Priv+wallet2_Priv,desc:ChatGroupName,Creator:wallet.address})
    }

    return (
        <>
            <TextInput
                // underlineColorAndroid={"black"}
                // errorMessage={}

                // value={ChatNum}
                onChangeText={async (value) => {
                    // console.log(value)
                    setChatGroupName(value);
                    if(value == "")
                    {
                        Toast.show("请输入群名称")
                        return ;
                    }
                    console.log("1")
                }}
                placeholder={"请输入群名称"}

                style={{marginTop:5,fontSize: 20,height:50,width:width,padding:0,paddingLeft:width*0.05,borderBottomWidth:1,borderBottomColor:"#F3F3F3",color:"black",fontWeight:"bold"}}
            />
            <TouchableHighlight
                underlayColor={ChatGroupName==""?"#A3F2FE":"#08A9D0"}
                style={{margin:25,padding:10,backgroundColor:ChatGroupName==""?"#A3F2FE":"#02CEFF",alignItems:"center",borderRadius:15}}
                onPress={async () => {
                if(ChatGroupName!=="")
                {
                    await createChatGroup();
                }
            }}>
                <Text style={{fontSize:18,color:"#fff"}}>创建群聊</Text>
            </TouchableHighlight>

        </>
    );
};

export default ChatGroupCreate;
